Technical Documentation Page

HTML 5

1) <!Doctype html>
is written so that the browser know the doctument has to be rendered according to the full standard mode decided by W3C for HTML ,CSS there are three modes:- quirks, almost standard and full standard as in starting the standard was for netscape browser and msft browser internet explorer.

2) Nowdays most of the browsers use full standard mode

3) <title>, <meta> tags link for favicon and author name.
<title> will define title for the page that will be displayed on tab of browser and on bookmarks.
<meta charset="utf-8">
will let our web page containg all sort of characters available including all makor languages of the world.
<meta name="author" content="Chris Mills">
AUTHOR NAME
<meta name="description" content="The MDN Web Docs Learning Area aims to provide complete beginners to the Web with all they need to know to get started with developing web sites and applications.">
for defining description that will also play role in SEO.
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
for displaying favicon
<link rel="stylesheet" href="css/style.css">
<script src="jsfolder/comp.js">
<html lang="en-US">
for defining the standard language for our web page.

4) Block Elements vs Inline Elements
Block Element
a) Block elements are the ones which contain all the space of parent element(container) they usually break the line and start from new line.
b) Block level may contain other block element, data or any inline element.
c) By default, block-level elements begin on new lines, but inline elements can start anywhere in a line.
ex:- <div>,<p>,<ul>,<ol>,<lo>,<table>,<section>

5) <div> is a block element,<span> is inline.
This means that to use them semantically, divs should be used to wrap sections of a document, while spans should be used to wrap small portions of text, images, etc.

6) Forms
HTML Forms are one of the main points of interaction between a user and a web site or application. They allow users to send data to the web site. Most of the time that data is sent to the web server, but the web page can also intercept it to use it on its own.
<form action="/my-handling-form-page" method="post">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="user_name">
</div>
<div>
<label for="mail">E-mail:</label>
<input type="email" id="mail" name="user_mail">
</div>
<div>
<label for="msg">Message:</label>
<textarea id="msg" name="user_message"></textarea>
</div>
</form>

7) Form Validation
Client-side validation is validation that occurs in the browser before the data has been submitted to the server. Client-side validation is more user-friendly than server-side validation because it gives an instant response.
a) Client-side validation is further subdivided into the following categories:
-JavaScript validation is coded using JavaScript. This validation is completely customizable.
-Built-in form validation uses HTML5 form validation features.
b) Server-side validation is validation that occurs on the server after the data has been submitted.
required keyword is used in html 5 to make it required , min length will determine minimum length that has to be entered max length is maximum length that has to be entered while min and max are for numbers.
type="password" type="number" type="text" type="email" are all valid for putting in input element
<form>
<div>
<label for="choose">Would you prefer a banana or a cherry?</label>
<input type="text" id="choose" name="i_like" required minlength="6" maxlength="6">
</div>
<div>
<label for="number">How many would you like?</label>
<input type="number" id="number" name="amount" value="1" min="1" max="10">
</div>
<div>
<button>Submit</button>
</div>
</form>

8) Some important tags for html forms
<input> it is a self closing tag
<textarea></textarea>
<label></label>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="password" minlength="8">
<input type="checkbox" name="vehicle1" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle2" value="Car"> I have a car<br>

9) The web is based on a very basic client/server architecture that can be summarized as follows: a client (usually a Web browser) sends a request to a server (most of the time a web server like Apache, Nginx, IIS, Tomcat, etc.), using the HTTP protocol. The server answers the request using the same protocol.
On the client side, an HTML form is nothing more than a convenient user-friendly way to configure an HTTP request to send data to a server. This enables the user to provide information to be delivered in the HTTP request.
<form action="http://foo.com" method="get">
action will contain the target api url or script where the data will go and method will contain the type of HTTP request most common ones that we will be using are (get) and (post).
required and

10) For Get request the data goes in the parameter GET (abc.com?say=Hi&to=mom)
Get request looks like
/?say=Hi&to=Mom HTTP/2.0
Host: foo.com
Post request looks like
POST / HTTP/2.0
Host: foo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13
say=Hi&to=Mom
Get is used when updates or insertion are made while POST is used when we have to pass data and expect something from server. Post sends the data in body so it is more secure so we should use post if data is critical.

11) The enctype attribute Section.This attribute lets you specify the value of the Content-Type HTTP header included in the request generated when the form is submitted. This header is very important because it tells the server what kind of data is being sent. By default, its value is application/x-www-form-urlencoded. In human terms, this means: "This is form data that has been encoded into URL parameters."
If you want to send files, you need to take three extra steps:

  • Set the method attribute to POST because file content can't be put inside URL parameters.

  • Set the value of enctype to multipart/form-data because the data will be split into multiple parts, one for each file plus one for the text data included in the form body (if text is also entered into the form).

  • Include one or more File picker widgets to allow your users to select the file(s) that will be uploaded.

  • For example:
    <form method="post" enctype="multipart/form-data">
    <div>
    <label for="file">Choose a file</label>
    <input type="file" id="file" name="myFile">
    </div>
    <div>
    <button>Send the file</button>
    </div>
    </form>

    12) Meta tags
    <meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScrit" > for SEO
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    CSS 3




    CSS 3 (Front End)

    1) Box properties Section
    Every element within a document is structured as a rectangular box inside the document layout, the size and "onion layers" of which can be tweaked using some specific CSS properties.

    width and height
    The width and height properties set the width and height of the content box, which is the area in which the content of the box is displayed — this content includes both text content set inside the box, and other boxes representing nested child elements.


    Padding
    Padding refers to the inner margin of a CSS box — between the outer edge of the content box and the inner edge of the border. The size of this layer can be set on all four sides at once with the padding shorthand property, or one side at a time with the padding-top, padding-right, padding-bottom and padding-left properties.

    Border
    The border of a CSS box sits between the outer edge of the padding and the inner edge of the margin. By default the border has a size of 0 — making it invisible — but you can set the thickness, style and color of the border to make it appear. The border shorthand property allows you to set all of these on all four sides at once, for example border: 1px solid black.

    Margin
    The margin surrounds a CSS box, and pushes up against other CSS boxes in the layout. It behaves rather like padding; the shorthand property is margin and the individual properties are margin-top, margin-right, margin-bottom, and margin-left.


    Overflow
    When you set the size of a box with absolute values (e.g. a fixed pixel width/height), the content may not fit within the allowed size, in which case the content overflows the box. To control what happens in such cases, we can use the overflow property. It takes several possible values, but the most common are:

    auto: If there is too much content, the overflowing content is hidden and scroll bars are shown to let the user scroll & view content.
    hidden: If there is too much content, the overflowing content is hidden.
    visible: If there is too much content, the overflowing content is shown outside of the box (this is usually the default behavior)

    Types of Boxes a) inline b) block c) inline-block

    A block box is defined as a box that's stacked upon other boxes (i.e. content before and after the box appears on a separate line), and can have width and height set on it. The whole box model as described above applies to block boxes.

    An inline box is the opposite of a block box: it flows with the document's text (i.e. it will appear on the same line as surrounding text and other inline elements, and its content will break with the flow of the text, like lines of text in a paragraph.) Width and height settings have no effect on inline boxes; any padding, margin and border set on inline boxes will update the position of surrounding text, but will not affect the position of surrounding block boxes.

    An inline-block box is something in between the first two: It flows with surrounding text and other inline elements without creating line breaks before and after it unlike a block box, but it can be sized using width and height and maintains its block integrity like a block box. It won't be broken across paragraph lines like an inline box. In the below example the inline-block box goes onto the 2nd line of text while keeping the shape of a box as there is not enough space for it on the first line, whereas inline box does break on multiple lines if there is not enough space — it loses the shape of a box.

    Note: By default, block level elements have display: block; set on them, and inline elements have display: inline; set on them.


    2) Box-sizing property set to border-box. This makes sure that the padding and border are included in the total width and height of the elements.


    Grid View
    A responsive grid-view often has 12 columns, and has a total width of 100%, and will shrink and expand as you resize the browser window.
    First ensure that all HTML elements have the box-sizing property set to border-box. This makes sure that the padding and border are included in the total width and height of the elements.

    Add the following code in your CSS:

    * {
    box-sizing: border-box;
    }

    .col-1 {width: 8.33%;}
    .col-2 {width: 16.66%;}
    .col-3 {width: 25%;}
    .col-4 {width: 33.33%;}
    .col-5 {width: 41.66%;}
    .col-6 {width: 50%;}
    .col-7 {width: 58.33%;}
    .col-8 {width: 66.66%;}
    .col-9 {width: 75%;}
    .col-10 {width: 83.33%;}
    .col-11 {width: 91.66%;}
    .col-12 {width: 100%;}

    [class*="col-"] {
    float: left;
    padding: 15px;
    border: 1px solid red;
    }

    <div class="row">
    <div class="col-3">...</div> <!-- 25% -->
    <div class="col-9">...</div> <!-- 75% -->
    </div>


    3) 9 basic principles of responsive web design
    a) Responsive vs Adaptive web design
    b) The flow
    c) Relative units
    d) Breakpoints
    e) Max and Min values
    f) Nested objects
    g) Mobile or Desktop first
    h) Web fonts vs System fonts
    i) Bitmap images vs Vectors (Always process pictures first)


    4) Flex Box

    #pond {
    display: flex;
    }

    flex-direction : row | row-reverse | column | column-reverse
    justify-content: flex-start | flex-end | center | space-between | space-around
    align-items: flex-start | flex-end | center | baseline | stretch
    order :(...,-2,-1,0,1,2,...)
    takes up the number default:0 higher the order it will switch towards (not just right but rather towards flex-end) and we get it -ve it will go (not just left but rather flex-start)
    align-self applied on sub elements takes input same as align-items but works only for single element;
    flex-wrap: nowrap | wrap | wrap-reverse
    nowrap: Every item is fit to a single line. (default)
    wrap: Items wrap around to additional lines.
    wrap-reverse: Items wrap around to additional lines in reverse.

    align-content: same as align-items;
    This can be confusing, but align-content determines the spacing between lines, while align-items determines how the items as a whole are aligned within the container. When there is only one line, align-content has no effect.

    align-self align-items feature for particular item
    flex-basis
    The flex-basis property specifies the initial size of the item before CSS makes adjustments with flex-shrink or flex-grow.
    The units used by the flex-basis property are the same as other size properties (px, em, %, etc.). The value auto sizes items based on the content.
    flex-grow
    flex-grow value of 1 and the other has a flex-grow value of 3, the one with the value of 3 will grow three times as much as the other.
    flex-shrink
    vice versa of flex-grow with same concept.
    flex
    flex: flex-grow-value flex-basis; shorthand of flex-grow and flex-basis combined


    5) Overriding CSS
    the class property will override body style if two classes are added and are overlapping properties then the one declared last in
    <style> tag will given preference to apply the style property, the id will override on classes but if a class property has
    !important tied to it it will be given preference.

    em and rem are used for relative units in css

    Use variable in css
    Declare var using --penguin-skin: gray;
    background: var(--penguin-skin); to change the background with color of penguin skin variable color
    IE does not support css variables so use fallbacks while using the variable

    By creating your variables in :root, they will be available throughout the whole web page.
    :root {
    --penguin-belly: pink;
    }
    we can override the variables in nested classes or other classes and can override :root defined value

    use position relative and then provide value to move the element relative to other elements in html
    h2 {
    position: relative;
    top: 25px;
    }

    The position:fixed keeps the block element fixed even when scrolling and top, bottom, left, right property can be used with it to move
    the elements or change their layout position position of element with respect to BROWSER, it also moves it out of general flow of html document, the position :absolute also moves the element out of normal flow of html document and we can use same left, right, top and bottom to move the position of element with respect to PARENT element.

    margin: auto will move the block element in center of page. we can also center an image with this while along with this just use
    display: block;

    The color wheel is a useful tool to visualize how colors relate to each other - it's a circle where similar hues are neighbors
    and different hues are farther apart. When two colors are opposite each other on the wheel, they are called complementary colors.
    They have the characteristic that if they are combined, they "cancel" each other out and create a gray color. However, when placed
    side-by- side, these colors appear more vibrant and produce a strong visual contrast

    One final point, each page should always have one (and only one) h1 element, which is the main subject of your content. This and the other headings are used in part by search engines to understand the topic of the page.

    ES 5



    ES5(ECMA Script 5)

    TODO : Improve the structuring

  • ES 5 PART I

  • 1) Null vs Undefined
    null is an assigned value. It means nothing.
    undefined means a variable has been declared but not defined yet.
    null is an object. undefined is of type undefined.
    null !== undefined but null == undefined.

    Statement does logical thing
    If else or condition statement or loop
    A statement is chained with ; while expression with , (comma)
    A statement is such that it can be placed where a value is required
    myVar
    x+3
    Bar(2,3)
    statement
    >console.log("a", "b");
    b
    Object literal vs block
    { foo: bar(3, 5) }
    The above line is both statement and expression
    function test(printTwo) { printing: { console.log("One"); if (!printTwo) break printing; console.log("Two"); } console.log("Three"); }

    function () { } function expression
    function foo() { } named function expression

    Control flow statements
    That change the flow of program on certain conditions or Control Flow is a fundamental concept in programming that allows you to dictate how your code runs under different conditions or until a certain condition is met.
    if else
    switch
    for
    for in
    nested if else
    while, do while, break, &&, ||
    for in (for parsing objects )

    Code could be self explanatory
    2 types of comment
    -Documentation comments
    -- Clarification comments
    Don't comment obvious things
    Comment if you have wasted lot of time to create a better solution and realize why I won't work and I is most likely otherwise developer too view code will also try to improve that particular code without thinking of the loophole.

    Strict mode makes several changes to normal JavaScript semantics:

    Eliminates some JavaScript silent errors by changing them to throw errors.

    Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode.

    Prohibits some syntax likely to be defined in future versions of ECMAScript.

    'use strict' in script
    'use strict' in function
    Modules are auto strict

    If a global variable is updated accidentally in some file it will throw error

    strict mode makes assignments which would otherwise silently fail to throw an exception. For example, NaN is a non-writable global variable. In normal code assigning to NaN does nothing; the developer receives no failure feedback. In strict mode assigning to NaN throws an exception. 

    JavaScript’s types:-
    The ECMAScript language types are
    Undefined,
    Null,
    Boolean
    String,
    Number,
    Object

    Static versus dynamic
    Static - > compile time
    Dynamic - > runtime

    JavaScript is dynamically typed, types of variables are generally not known at compile time

    Statically type-checked languages perform this kind of check at compile time, dynamically type-checked languages at runtime
    JavaScript performs a very limited kind of dynamic type checking,

    > var foo = null; > foo.prop TypeError: Cannot read property 'prop' of null Mostly, however, things silently fail or work. 


    coersion
     JavaScript, the main way of dealing with a value whose type doesn’t fit is to coerce it to the correct type. Coercion means implicit type conversion. Most operands coerce: > '3' * '4' 12 JavaScript has internal functions for performing this kind of conversion explicitly [1]. Some of them can be accessed in the language, via the functions Boolean, Number, String, Object. > Number(true) 1 > Number('123') 123 > String(true) 'true'
    typeof([1,2,3]) is object as its an ordered list of values mapped to index for JS

    Object is reference type all other types mentioned above are primitives including a new element named symbol

    // Outputs: "Objects coerce to true." if ({}) { console.log("Objects coerce to true."); }

    var functionTrue = Boolean(true); var functionFalse = Boolean(false);

    But the Boolean function can also be used as a constructor with the new keyword:

    var constructorTrue = new Boolean(true); var constructorFalse = new Boolean(false);

    The tricky thing here is that when Booleanis used as a constructor, it doesn't return a primitive. Instead it returns an object.

    // Outputs: true console.log(primitiveTrue); // Outputs: true console.log(functionTrue); // Outputs: Boolean {} console.log(constructorTrue);

    // Two approaches to coercing 0 into false var byFunction = Boolean(0); var byNotNot = !!0;

    // Outputs: "My false Boolean object is truthy!" if (constructorFalse) { console.log("My false Boolean object is truthy!"); } else { console.log("My false Boolean object is falsy!"); }

    Use valueOf() for correct truthy false value in case of Boolean Object

    Null

    Null means an empty or non-existent value. Null is assigned, and explicitly means nothing.null is also an object
    console.log(typeof test1);
    // object

    USE === instead of == triple === checks both data type and value comparison

    In JavaScript there are only six falsy values.

    false

    0 (zero)

    “” (empty string)

    null

    undefined

    NaN (Not A Number)

    Comparing false, 0, and "" with loose equality (==) will result in equality:

    false == 0
    // true0 == ""
    // true"" == false
    // true

    null and undefined are only equal to themselves:

    null == null
    undefined == undefined
    null == undefined// true

    NaN isn’t equivalent to anything (not even itself!):

    NaN == null
    NaN == undefined
    NaN == NaN
    // false

    3 === '3'
    // false (Number compared to String)3 == '3'
    // true

    Logical operators
    && logical AND
    || logical OR
    ! logical NOT

    Short circuit evaluation

    function potentiallyBuggyCodeAvailable(){

    code;

    debugger;

    }


    When the debugger is invoked, execution is paused at the debugger statement. It is like a breakpoint in the script source.
    Use debugging tools in web browser developers tools

    Parameters are used to define a function. They are also called formal parameters and formal arguments. In the following example, param1 and param2 are parameters:

    function foo(param1, param2) {...}

    Arguments are used to invoke a function. They are also called actual parameters and actual arguments. In the following example, 3 and 7 are arguments:

    foo(3, 7);

    Defining Functions

    All functions are objects, instances of Function:

    function id(x) { return x; } console.log(id instanceof Function); // true

    Therefore, functions get their methods from Function.prototype.

    Function Expressions

    A function expression produces a value—a function object. For example:

    var add = function (x, y) { return x + y }; console.log(add(2, 3)); // 5

    The value produced by a function expression can be assigned to a variable (as shown in the example), passed as an argument to another function, and more. Because normal function expressions don’t have a name, they are also called anonymous function expressions.

    Named function expressions

    You can give a function expression a name. Named function expressions allow a function expression to refer to itself, which is useful for self-recursion:

    var fac = function me(n) { if (n > 0) { return n * me(n-1); } else { return 1; } }; console.log(fac(3)); // 6

    NOTE

    The name of a named function expression is only accessible inside the function expression:


    Function Declarations/statement
    The following is a function declaration:
    function add(x, y) { return x + y; }

    The Function Constructor

    The constructor Function() evaluates JavaScript code stored in strings. For example, the following code is equivalent to the previous example:

    var add = new Function('x', 'y', 'return x + y');


    foo(); // TypeError
    bar(); // ReferenceError
    var foo = function bar() { // ... };

    This snippet is more accurately interpreted (with hoisting) as:

    var foo; foo(); // TypeError bar(); // ReferenceError foo = function() { var bar = ...self... // ... }

    First JS code compiles and then function declarations and variable declarations are hoisted i.e., the declaration part is seen on the top of the scope and assignment remains at same place except function expressions.

    for undefined value type error comes this the case when we try to print variable that is declared but the not initialized while in case of function expression referenced error comes


    Functions First

    Both function declarations and variable declarations are hoisted. But a subtle detail (that can show up in code with multiple "duplicate" declarations) is that functions are hoisted first, and then variables.

    Consider:

    foo(); // 1 var foo; function foo() { console.log( 1 ); } foo = function() { console.log( 2 ); };

    1 is printed instead of 2! This snippet is interpreted by the Engineas:

    function foo() { console.log( 1 ); } foo(); // 1 foo = function() { console.log( 2 ); };

    While multiple/duplicate vardeclarations are effectively ignored, subsequent function declarations dooverride previous ones.


    foo(); // 3 function foo() { console.log( 1 ); } var foo = function() { console.log( 2 ); }; function foo() { console.log( 3 ); }

    We can be tempted to look at var a = 2; as one statement, but the JavaScript Engine does not see it that way. It sees var a and a = 2as two separate statements, the first one a compiler-phase task, and the second one an execution-phase task.

    What this leads to is that all declarations in a scope, regardless of where they appear, are processed first before the code itself is executed. You can visualize this as declarations (variables and functions) being "moved" to the top of their respective scopes, which we call "hoisting".


    this keyword in JavaScript
    In functions: this is an extra, often implicit, parameter.

    Outside functions (in the top-level scope): thisrefers to the global object in browsers and to a module’s exports in Node.js.

    In a string passed to eval(): eval() either picks up the current value of this or sets it to the global object, depending on whether it is called directly or indirectly.


    First-Class Functions vs Higher-Order Functions

    What’s the difference?

    First class functions are treated like objects. Higher order functions either accept a function as an argument, return a function, or both.



     real functions, the value of this depends on the mode one is in:

    Sloppy mode: this refers to the global object(window in browsers). function sloppyFunc() { console.log(this === window); // true } sloppyFunc();

    Strict mode: this has the value undefined. function strictFunc() { 'use strict'; console.log(this === undefined); // true } strictFunc();

    Functions become constructors if you invoke them via the new operator. That operator creates a new object and passes it to the constructor via this: var savedThis; function Constr() { savedThis = this; } var inst = new Constr(); console.log(savedThis === inst); // true

    this in methods

    In methods, things are similar to more traditional object-oriented languages: this refers to the receiver, the object on which the method has been invoked. var obj = { method: function () { console.log(this === obj); // true } } obj.method();

    this in the top-level scope

    In browsers, the top-level scope is the global scope and this refers to the global object (like window does): <script> console.log(this === window); // true </script> In Node.js, you normally execute code in modules. Therefore, the top-level scope is a special module scope: // `global` (not `window`) refers to global object: console.log(Math === global.Math); // true // `this` doesn’t refer to the global object: console.log(this !== global); // true // `this` refers to a module’s exports: console.log(this === module.exports); // true

    eval() can be called either directly (via a real function call) or indirectly (via some other means). The details are explained here.

    If eval() is called indirectly, this refers to the global object:

    > (0,eval)('this === window') true

    JS don't have block scope it's either local scope or global scope and if we don't define variable using var or let keyword it get s declared in global scope.

    For browser or for web developer per se the global scope is windows object and( global object for nodejs).

    setTimeout Variables are Executed in the Global Scope, this keyword used in setTimeout refers to the global object not to var object it is declared in

    Scope and closures
    JavaScript falls under the general category of "dynamic" or "interpreted" languages, it is in fact a compiled language. It is notcompiled well in advance, as are many traditionally-compiled languages, nor are the results of compilation portable among various distributed systems.


    Let's meet the cast of characters that interact to process the program var a = 2;, so we understand their conversations that we'll listen in on shortly:

    Engine: responsible for start-to-finish compilation and execution of our JavaScript program.

    Compiler: one of Engine's friends; handles all the dirty work of parsing and code-generation (see previous section).

    Scope: another friend of Engine; collects and maintains a look-up list of all the declared identifiers (variables), and enforces a strict set of rules as to how these are accessible to currently executing code.

    var a = 2;.

    The first thing Compiler will do with this program is perform lexing to break it down into tokens, which it will then parse into a tree. 

    To summarize: two distinct actions are taken for a variable assignment: First, Compiler declares a variable (if not previously declared in the current scope), and second, when executing, Engine looks up the variable in Scopeand assigns to it, if found

    LHS and RHS lookup
    When I say:

    console.log( a );

    The reference to a is an RHS reference, because nothing is being assigned to a here. Instead, we're looking-up to retrieve the value of a, so that the value can be passed to console.log(..).

    By contrast:

    a = 2;

    The reference to a here is an LHS reference, because we don't actually care what the current value is, we simply want to find the variable as a target for the = 2 assignment operation.



    Engine scope and compiler
    function foo(a) { console.log( a ); // 2 } foo( 2 );

    Let's imagine the above exchange (which processes this code snippet) as a conversation. The conversation would go a little something like this:

    Engine: Hey Scope, I have an RHS reference for foo. Ever heard of it?

    Scope: Why yes, I have. Compiler declared it just a second ago. He's a function. Here you go.

    Engine: Great, thanks! OK, I'm executing foo.

    Engine: Hey, Scope, I've got an LHS reference for a, ever heard of it?

    Scope: Why yes, I have. Compiler declared it as a formal parameter to foo just recently. Here you go.

    Engine: Helpful as always, Scope. Thanks again. Now, time to assign 2 to a.

    Engine: Hey, Scope, sorry to bother you again. I need an RHS look-up for console. Ever heard of it?

    Scope: No problem, Engine, this is what I do all day. Yes, I've got console. He's built-in. Here ya go.

    Engine: Perfect. Looking up log(..). OK, great, it's a function.

    Engine: Yo, Scope. Can you help me out with an RHS reference to a. I think I remember it, but just want to double-check.

    Scope: You're right, Engine. Same guy, hasn't changed. Here ya go.

    Engine: Cool. Passing the value of a, which is 2, into log(..).


    If an RHS look-up fails to ever find a variable, anywhere in the nested Scopes, this results in a ReferenceError being thrown by the Engine. It's important to note that the error is of the type ReferenceError.

    By contrast, if the Engine is performing an LHS look-up and arrives at the top floor (global Scope) without finding it, and if the program is not running in "Strict Mode" [^note-strictmode], then the global Scopewill create a new variable of that name in the global scope, and hand it back to Engine.

    "No, there wasn't one before, but I was helpful and created one for you."

    "Strict Mode" [^note-strictmode], which was added in ES5, has a number of different behaviors from normal/relaxed/lazy mode. One such behavior is that it disallows the automatic/implicit global variable creation. In that case, there would be no global Scope'd variable to hand back from an LHS look-up, and Engine would throw a ReferenceError similarly to the RHS case.

    Now, if a variable is found for an RHS look-up, but you try to do something with its value that is impossible, such as trying to execute-as-function a non-function value, or reference a property on a null or undefined value, then Engine throws a different kind of error, called a TypeError.

    ReferenceError is Scoperesolution-failure related, whereas TypeError implies that Scoperesolution was successful, but that there was an illegal/impossible action attempted against the result

    Lexical scope is used in JS
    eval is used to cheat the lexical scope that states that first innermost scope will check and so on lastly the global scope
    And shadowing can also be done that is naming the same variable in different scopes
    function foo(str, a) { eval( str ); // cheating! console.log( a, b ); } var b = 2; foo( "var b = 3;", 1 ); // 1 3

    function foo(str) { "use strict"; eval( str ); console.log( a ); // ReferenceError: a is not defined } foo( "var a = 2"

    with (keyword ) is other way of cheating lexical scope
    function foo(obj) { with (obj) { a = 2; } } var o1 = { a: 3 }; var o2 = { b: 3 }; foo( o1 ); console.log( o1.a ); // 2 foo( o2 ); console.log( o2.a ); // undefined console.log( a ); // 2 -- Oops,
    Lexical scope means that scope is defined by author-time decisions of where functions are declared


    JS compiler does
    1) Lexing
    2) parsing ( taking token and creating AST Abstract Syntax Tree)
    3) Code-Generation: the process of taking an AST and turning it into executable code. 


    function sayHello() { console.log("hello");};var func = sayHello;

    You are assigning the variable func a reference to the function sayHello, nota copy. Here, func is simply an alias to sayHello. Anything you do on the alias you will actually be doing on the original function. For example:

    func.answer = 42;console.log(sayHello.answer); // prints 42

    Scopes have a lifetime

    When you call a function, you create a scope during the execution of that function. Then that scope goes away.

    When you call the function a second time, you create a new different scope during the second execution. Then this second scope goes away as well.

    function printA() { console.log(answer); var answer = 1;};printA(); // this creates a scope which gets discarded right afterprintA(); // this creates a new different scope which also gets discarded right after;

    Closures span multiple scopes

    When you define a function, a closure gets created

    Unlike scopes, closures are created when you define a function, not when you execute it. Closures also don’t go away after you execute that function.

    You can access the data in a closure long after a function is defined and after it gets executed as well.

    A closures encompasses everything the defined function can access. This means the defined function’s scope, and all the nested scopes between the global scope and the defined function scope plus the global scope itself.

    var G = 'G';// Define a function and create a closurefunction functionA() { var A = 'A' // Define a function and create a closure function functionB() { var B = 'B' console.log(A, B, G); } functionB(); // prints A, B, G // functionB closure does not get discarded A = 42; functionB(); // prints 42, B, G}functionA();

    But the relation between scopes and closures is not always simple like this. Things become different when the defining and invoking of functions happen in different scopes. Let me explain that with an example:

    var v = 1;var f1 = function () { console.log(v);}var f2 = function() { var v = 2; f1(); // Will this print 1 or 2?};f2();






  • ES5 Part II




  • But the relation between scopes and closures is not always simple like this. Things become different when the defining and invoking of functions happen in different scopes. Let me explain that with an example:

    var v = 1;var f1 = function () { console.log(v);}var f2 = function() { var v = 2; f1(); // Will this print 1 or 2?};f2();

    What do you think the above example will print? The code is simple, f1()prints the value of v, which is 1 on the global scope, but we execute f1()inside of f2(), which has a different vthat’s equal to 2. Then we execute f2().

    Will this code print 1 or 2?

    If you’re tempted to say 2, you’ll be surprised. This code will actually print 1. The reason is, scopes and closures are different. The console.log line will use the closure of f1(), which is created when we define f1(), which means the closure of f1() gives us access to only the scope of f1() plus the global scope. The scope where we execute f1() does not affect that closure. In fact, the closure of f1() will not give us access to the scope of f2() at all. If you remove the global v variable and execute this code, you’ll get a reference error:

    var f1 = function () { console.log(v);}var f2 = function() { var v = 2; f1(); // ReferenceError: v is not defined};f2();

    Since closures give us references to variables in scopes, the access that they give us means both read and write, not just read.

    // ReferenceError: funcName is not defined funcName(); // TypeError: undefined is not a function varName(); var varName = function funcName() { console.log("Definition not hoisted!"); };

    As you can see, the function's name doesn't get hoisted if it is part of a function expression.

    A Tricky problem in JS
    // interviewer: what will the following code output?const arr = [10, 12, 15, 21];for (var i = 0; i < arr.length; i++) { setTimeout(function() { console.log('Index: ' + i + ', element: ' + arr[i]); }, 3000);}

    This question deals with the topics: closures, setTimeout, and scoping. The correct answer to this is question is:

    Index: 4, element: undefined(printed 4 times).

    setTimeout(function() {//code}, 1000)
    setInterval
    clearInterval(timeoutId) ;


    JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method

    Unassigned properties of an object are undefined (and not null).
    However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. 

    JavaScript object property names (keys) can only be strings or Symbols You can also access properties by using a string value that is stored in a variable:

    var propertyName = 'make';
    myCar[propertyName] = 'Ford';

    Starting with ECMAScript 5, there are three native ways to list/traverse object properties:
    for...in loop
    Object.keys(o)
    Object.getOwnPropertyNames(o)

    To create new variable
    1) use object initializers
    {s:2,p:3}
    2) Using constructor
    function Car(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
    }
    var mycar = new Car('Eagle', 'Talon TSi', 1993);

    JavaScript is a prototype-based language, meaning object properties and methods can be shared through generalized objects that have the ability to be cloned and extended. This is known as prototypical inheritance and differs from class inheritance. 

    let x = new Object().

    The double square brackets that enclose [[Prototype]] signify that it is an internal property, and cannot be accessed directly in code.

    To find the [[Prototype]] of this newly created object, we will use the getPrototypeOf() method.

    Object.getPrototypeOf(x);
    JavaScript has a [[Prototype]] as it creates a way for any two or more objects to be linked.

    When you attempt to access a property or method of an object, JavaScript will first search on the object itself, and if it is not found, it will search the object's [[Prototype]]. If after consulting both the object and its [[Prototype]] still no match is found, JavaScript will check the prototype of the linked object, and continue searching until the end of the prototype chain is reached.

    When you attempt to access a property or method of an object, JavaScript will first search on the object itself, and if it is not found, it will search the object's [[Prototype]]. If after consulting both the object and its [[Prototype]] still no match is found, JavaScript will check the prototype of the linked object, and continue searching until the end of the prototype chain is reached.


    Introduction

    JavaScript is a prototype-based language, meaning object properties and methods can be shared through generalized objects that have the ability to be cloned and extended. This is known as prototypical inheritance and differs from class inheritance. Among popular object-oriented programming languages, JavaScript is relatively unique, as other prominent languages such as PHP, Python, and Java are class-based languages, which instead define classes as blueprints for objects.

    In this tutorial, we will learn what object prototypes are and how to use the constructor function to extend prototypes into new objects. We will also learn about inheritance and the prototype chain.

    JavaScript Prototypes

    In Understanding Objects in JavaScript, we went over the object data type, how to create an object, and how to access and modify object properties. Now we will learn how prototypes can be used to extend objects.

    Every object in JavaScript has an internal property called [[Prototype]]. We can demonstrate this by creating a new, empty object.

    let x = {};

    This is the way we would normally create an object, but note that another way to accomplish this is with the object constructor: let x = new Object().

    The double square brackets that enclose [[Prototype]] signify that it is an internal property, and cannot be accessed directly in code.

    To find the [[Prototype]] of this newly created object, we will use the getPrototypeOf() method.

    Object.getPrototypeOf(x);

    The output will consist of several built-in properties and methods.

    Output

    {constructor: ƒ, _defineGetter: ƒ, __defineSetter_: ƒ, …}

    Another way to find the [[Prototype]]is through the _proto_ property. _proto_ is a property that exposes the internal [[Prototype]] of an object.

    It is important to note that ._proto_is a legacy feature and should not be used in production code, and it is not present in every modern browser. However, we can use it throughout this article for demonstrative purposes.

    x._proto_;

    The output will be the same as if you had used getPrototypeOf().

    Output

    {constructor: ƒ, _defineGetter: ƒ, __defineSetter_: ƒ, …}

    It is important that every object in JavaScript has a [[Prototype]] as it creates a way for any two or more objects to be linked.

    Objects that you create have a [[Prototype]], as do built-in objects, such as Date and Array. A reference can be made to this internal property from one object to another via the prototypeproperty, as we will see later in this tutorial.

    Prototype Inheritance

    When you attempt to access a property or method of an object, JavaScript will first search on the object itself, and if it is not found, it will search the object's [[Prototype]]. If after consulting both the object and its [[Prototype]] still no match is found, JavaScript will check the prototype of the linked object, and continue searching until the end of the prototype chain is reached.

    At the end of the prototype chain is Object.prototype. All objects inherit the properties and methods of Object. Any attempt to search beyond the end of the chain results in null.

    In our example, x is an empty object that inherits from Object. x can use any property or method that Object has, such as toString().

    x.toString();

    Output

    [object Object]

    This prototype chain is only one link long. x -> Object. We know this, because if we try to chain two [[Prototype]]properties together, it will be null.

    x._proto.proto_;

    Output

    null

    Let's look at another type of object. If you have experience Working with Arrays in JavaScript, you know they have many built-in methods, such as pop() and push(). The reason you have access to these methods when you create a new array is because any array you create has access to the properties and methods on the Array.prototype.

    We can test this by creating a new array.

    let y = [];

    Keep in mind that we could also write it as an array constructor, let y = new Array().

    If we take a look at the [[Prototype]] of the new y array, we will see that it has more properties and methods than the xobject. It has inherited everything from Array.prototype.

    y._proto_; [constructor: ƒ, concat: ƒ, pop: ƒ, push: ƒ, …]
    This is the reason we can push and pop from the array

    y._proto_ === Array.prototype; // true y._proto.proto_ === Object.prototype; // true

    We can also use the isPrototypeOf()method to accomplish this.

    Array.prototype.isPrototypeOf(y); // true Object.prototype.isPrototypeOf(Array); // true

    We can use the instanceof operator to test whether the prototype property of a constructor appears anywhere within an object's prototype chain.

    y instanceof Array; // true

    To summarize, all JavaScript objects have a hidden, internal [[Prototype]]property (which may be exposed through _proto_ in some browsers). Objects can be extended and will inherit the properties and methods on [[Prototype]] of their constructor.

    These prototypes can be chained, and each additional object will inherit everything throughout the chain. The chain ends with the Object.prototype.

    We have seen some built-in JavaScript constructors, such as new Array() and new Date(), but we can also create our own custom templates from which to build new objects.

    // Add greet method to the Hero prototype Hero.prototype.greet = function () { return `${this.name} says hello.`; }

    function Point(x, y) { this.x = x; this.y = y; } Point.prototype = { dist: function () { return Math.sqrt((this.x*this.x)+(this.y*this.y)); }, toString: function () { return "("+this.x+", "+this.y+")"; } } We assign an object to Point.prototype, via an object initializer with two properties dist and toString. Now there is a clear separation of responsibility: The constructor is responsible for setting up instance-specific data, the prototype contains shared data (i.e., the methods). Note that prototypes are highly optimized in JavaScript engines, so there is usually no performance penalty for putting methods there. Methods are called just like before, you don’t notice whether they are stored in the instance or in the prototype

    To fix extend(), we must ensure that only own properties of source are considered. function extend(target, source) { for (var propName in source) { // Is propName an own property of source? if (source.hasOwnProperty(propName)) { // (1) target[propName] = source[propName]; } } return target; } There is one more problem: The above code fails if source has an own property whose name is “hasOwnProperty” [3]:

    var proto = { bla: true }; var obj = Object.create(proto); obj.foo = 123; obj.bar = "abc"; obj has both inherited and own properties: > obj.bla true > obj.foo 123

    var obj = Object.create(proto, { foo: { value: 123 }, bar: { value: "abc" } });

    Object.keys()
    const object1 = {
    a: 'somestring',
    b: 42,
    c: false
    };

    console.log(Object.keys(object1));
    // expected output: Array ["a", "b", "c"]

    language = {
    set current(name) {
    this.log.push(name);
    },
    log: []
    }

    language.current = 'EN';
    language.current = 'FA';

    console.log(language.log);
    // expected output: Array ["EN", "FA"]

    var obj = {
    log: ['a', 'b', 'c'],
    get latest() {
    if (this.log.length == 0) {
    return undefined;
    }
    return this.log[this.log.length - 1];
    }
    }

    console.log(obj.latest);
    // expected output: "c"


    if (somethingBadHappened) { throw new Error('Something bad happened'); }

    Any value can be thrown:

    function throwIt(exception) { try { throw exception; } catch (e) { console.log('Caught: '+e); } }

    Array
    Array in JS are non homogeneous and non contiguous and the memory allocation is not together
    var array1 = [1, 4, 9, 16];

    // pass a function to map
    const map1 = array1.map(x => x * 2);

    console.log(map1);
    // expected output: Array [2, 8, 18, 32]

    const array1 = [1, 2, 3, 4];
    const reducer = (accumulator, currentValue) => accumulator + currentValue;

    // 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer));
    // expected output: 10

    // 5 + 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer, 5));
    // expected output: 15

    var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

    const result = words.filter(word => word.length > 6);
    console.log(result);
    // expected output: Array ["exuberant", "destruction", "present"]

    var array1 = ['a', 'b', 'c'];

    array1.forEach(function(element) {
    console.log(element);
    });

    // expected output: "a"
    // expected output: "b"
    // expected output: "c"

    var array1 = ['a', 'b', 'c'];

    Mutating
    array.push() and array.ushift().
    array.pop() removes an item at the end of the array
    array.shift() removes an item at the beginning of the array.

    let mutatingRemove = ['a', 'b', 'c', 'd', 'e']; mutatingRemove.splice(0,2 ); // ['c', 'd', 'e']
    array.splice()


    Non-Mutating
     array.concat()
    ... Spread operator
    // use const const arr1 = ['a', 'b', 'c', 'd', 'e']; const arr2 = arr1.filter(a => a !== 'e'); // ['a', 'b', 'c', 'd'] // OR const arr2 = arr1.filter(a => { return a !== 'e'; }); // ['a', 'b', 'c', 'd']


    array.slice() takes two parameters.

    The first parameter is the index where the copy should begin.

    The second parameter is the index where the copy should end. This end index is non-inclusive.
    array.map

    To create a regular expression
    1)var re = /ab+c/; //using enclosing slashes
    2) var re = new RegExp('ab+c'); //using RegExp constructor

    match a single 'a' followed by zero or more 'b's followed by 'c', you'd use the pattern /ab*c


    Date Object
    let now = new Date(); // will display method call time date and time

    var today = new Date();
    var birthday = new Date('December 17, 1995 03:24:00');
    var birthday = new Date('1995-12-17T03:24:00');
    var birthday = new Date(1995, 11, 17);
    var birthday = new Date(1995, 11, 17, 3, 24, 0);

    var date1 = new Date('December 17, 1995 03:24:00');
    // Sun Dec 17 1995 03:24:00 GMT...

    var date2 = new Date('1995-12-17T03:24:00');
    // Sun Dec 17 1995 03:24:00 GMT...

    console.log(date1 === date2);
    // expected output: false;

    console.log(date1 - date2);
    // expected output 0

    JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

    JSON is built on two structures:

    A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
    An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.


    Working with JSON

    parse

    stringify

    difference between objects and JSON


    -Sharing global variables between unrelated code is a big no-no in development.

    Modules are reusablw chunk of code in ES5 that we can reuse in any project and in the same project the dependency of one module should be
    very less on other modules.

    we can use closure based way of creating and using functions to avoid global namespacing pollution using

    var myGradesCalculate = (function () {

    // Keep this variable private inside this closure scope
    var myGrades = [93, 95, 88, 0, 55, 91];

    var average = function() {
    var total = myGrades.reduce(function(accumulator, item) {
    return accumulator + item;
    }, 0);

    return'Your average grade is ' + total / myGrades.length + '.';
    };

    var failing = function() {
    var failingGrades = myGrades.filter(function(item) {
    return item < 70;
    });

    return 'You failed ' + failingGrades.length + ' times.';
    };

    // Explicitly reveal public pointers to the private functions
    // that we want to reveal publicly

    return {
    average: average,
    failing: failing
    }
    })();

    myGradesCalculate.failing(); // 'You failed 2 times.'
    myGradesCalculate.average(); // 'Your average grade is 70.33333333333333.'

    or ew can also use commonJS that works like NodeJs modeule approach.

    commonJS code
    function myModule() {
    this.hello = function() {
    return 'hello!';
    }

    this.goodbye = function() {
    return 'goodbye!';
    }
    }

    module.exports = myModule;

    There are two obvious benefits to this approach over the module patterns we discussed before:

    1. Avoiding global namespace pollution
    2. Making our dependencies explicit

    AMD
    CommonJS is all well and good, but what if we want to load modules asynchronously? The answer is called Asynchronous Module Definition, or AMD for short.

    Loading modules using AMD looks something like this:

    define(['myModule', 'myOtherModule'], function(myModule, myOtherModule) {
    console.log(myModule.hello());
    });

    Creating and using code using ES6 Modules

    // lib/counter.js

    var counter = 1;

    function increment() {
    counter++;
    }

    function decrement() {
    counter--;
    }

    module.exports = {
    counter: counter,
    increment: increment,
    decrement: decrement
    };


    // src/main.js

    var counter = require('../../lib/counter');

    counter.increment();
    console.log(counter.counter); // 1


    Module bundling

    What is module bundling?
    On a high level, module bundling is simply the process of stitching together a group of modules (and their dependencies) into a single file (or group of files) in the correct order.

    As with all aspects of web development, the devil is in the details. :)

    Why bundle modules at all?
    When you divide your program into modules, you typically organize those modules into different files and folders. Chances are, you’ll also have a group of modules for the libraries you’re using, like Underscore or React.

    As a result, each of those files has to be included in your main HTML file in a <script> tag, which is then loaded by the browser when a user visits your home page. Having separate <script> tags for each file means that the browser has to load each file individually: one… by… one.

    …Which is bad news for page load time.

    To get around this problem, we bundle, or “concatenate” all our files into one big file (or a couple files as the case may be) in order to reduce the number of requests. When you hear developers talking about the “build step” or “build process,” this is what they’re talking about.


    Task runners like Gulp and Grunt make concatenation and minification straightforward for developers, ensuring that human-readable code stays exposed for developers while machine-optimized code gets bundled for browsers.

    What are the different ways to bundle modules?
    Concatenating and minifying your files works great when you’re using one of the standard module patterns (discussed in the previous post) to define your modules. All you’re really doing is mashing together a bunch of plain vanilla JavaScript code.

    However, if you’re adhering to non-native module systems that browsers can’t interpret like CommonJS or AMD (or even native ES6 module formats), you’ll need to use a specialized tool to convert your modules into properly-ordered browser-friendly code. That’s where Browserify, RequireJS, Webpack, and other “module bundlers” or “module loaders” come into play.

    In addition to bundling and/or loading your modules, module bundlers offer a ton of additional features like auto-recompiling code when you make a change or producing source maps for debugging.

    Here are a couple of the options for building/converting ES6 modules to work in the browser, with #1 being the most common approach today:

    Use a transpiler (e.g. Babel or Traceur) to transpile your ES6 code to ES5 code in either CommonJS, AMD, or UMD format. Then pipe the transpiled code through a module bundler like Browserify or Webpack to create one or more bundled files.

    Deep Copy and shallow copy
    1) when we initialize one object variable with another we just pass the reference.
    2) every object in JS has Object class in it's prototype chain.
    3) On using a for in loop to individually copy all the elements
    objCopy object has a new Object.prototype method different from the mainObj object prototype method, which is not what we want. We want an exact copy of the original object.


    https://scotch.io/bar-talk/copying-objects-in-javascript


    instanceof, typeof, new


    Pure, total and partial functions

    Pure Functions
    They also makes maintaining and refactoring code much easier. You can change a pure function and not have to worry about unintended side effects messing up the entire application and ending up in debugging hell.

    When used correctly the use of pure functions produces better quality code. It’s a cleaner way of working with lots of benefits.


    ES 6



    ES 6 (ECMA SCRIPT 6) (In Progress)

    1) let vs var
    var has enclosing function scope while let has block scope (block scope is introduced in ES6).
    function varTest() {
    var x = 1;
    if (true) {
    var x = 2; // same variable!
    console.log(x); // 2
    }
    console.log(x); // 2
    }

    function letTest() {
    let x = 1;
    if (true) {
    let x = 2; // different variable
    console.log(x); // 2
    }
    console.log(x); // 1
    }

    let does not create global scope variables
    var x = 'global';
    let y = 'global';
    console.log(this.x); // "global"
    console.log(this.y); // undefined


    2) string literals
    var a = 5;
    var b = 10;
    console.log(`Fifteen is ${a + b} and
    not ${2 * a + b}.`);
    // "Fifteen is 15 and
    // not 20."






    git


    1) Centralized Version Control
    Centralized version control systems are based on the idea that there is a single “central” copy of your project somewhere (probably on a server), and programmers will “commit” their changes to this central copy.
    “Committing” a change simply means recording the change in the central system. Other programmers can then see this change. They can also pull down the change, and the version control tool will automatically update the contents of any files that were changed. Ex:- Subversion
    Distributed Version Control
    These systems do not necessarily rely on a central server to store all the versions of a project’s files. Instead, every developer “clones” a copy of a repository and has the full history of the project on their own hard drive. This copy (or “clone”) has all of the metadata of the original.ex:- Git


    2) Central Repository
    Having a central repository is optional in distributed version control system.In both pulling and pushing you move changesets (changes to files groups as coherent wholes), not single-file diffs.


    3) Advantages of DVCS over CVCS
    Performing actions other than pushing and pulling changesets is extremely fast because the tool only needs to access the hard drive, not a remote server.
    Committing new changesets can be done locally without anyone else seeing them. Once you have a group of changesets ready, you can push all of them at once.
    Everything but pushing and pulling can be done without an internet connection. So you can work on a plane, and you won’t be forced to commit several bugfixes as one big changeset.
    Since each programmer has a full copy of the project repository, they can share changes with one or two other people at a time if they want to get some feedback before showing the changes to everyone.


    4) Branching
    Branches in Git are incredibly lightweight as well. They are simply pointers to a specific commit
    branch name should follow camel case convention
    To merge two project branches we can use merge operation or rebasing.
    Each branch provide us to work on our project without messing with our main production line code.


    5) Commands (Important)
    a) git checkout branch-name to move to other branch
    b) git commit (to make commit)
    c) git commit -m "commit message" to commit with message
    d) git branch to display all the branches
    e) git branch branch-name to create new branch
    f) git merge br-name this will merge the branch br-name in the branch you have called this command.
    g) git init to initialize a new repository
    h) git clone url to clone the remote repository in yout local system
    i) git rebase master

    will combine and move the present series of commmits from the point they have divergered from master and will put
    them in front of master and msater will become their ancestor and the old series of commits will be left where they were.


    6) HEAD
    HEAD is the symbolic name for the currently checked out commit -- it's essentially what commit you're working on top of.
    git checkout commit-hash will take our HEAD to particular commit
    relative refs
    instead of moving head to a commit using hash value which is very long we use relative refs
    git checkout hash-code to move to commit (detaching from branch and moving to commit)
    git checkout HEAD^ move to parent commit of present HEAD or commit
    git checkout HEAD~4 move to present commit's 4th previous commit from HEAD.


    To move a branch to different commit we have to use
    git branch -f master HEAD
    git branch -f bugFix HEAD~3

    To move or roll back the changes
    git reset HEAD^ for local system this will delete the new commit
    git revert HEAD for remote branch this cannot delete as others are usign that commit so it creates a new commit with old value

    Other way of using git reset:-
    git reset --soft commit-hash
    git reset --soft commit-hash
    git reset --soft commit-hash
    In other words, --soft is discarding last commit, --mix is discarding last commit and add, --hard is discarding last commit,add and any changes you made on the codes which is the same with git checkout HEAD


    7) git cherry pick c4 c7
    when called after taking HEAD to master will copy and create new commits on master an move head to c7'
    to check commit history use


    8) git log
    git log - p commit to history with patch outputs
    git log - - stat show statistics of modified flies
    git log - - shortstat display only the changes lines insertion /deletion of got log - - stat
    git log - 2 shows last two commits
    git log - -pretty=oneline
    git log - -pretty=short/full


    9) Branch
    Branch is a way to request new working directory, staging area and project history it is a independent line of development
    Branch servers as abstraction to edit /stage /commit process
    git branch - d branch-name
    safe delete send error of branch notification merged
    git branch - D branch-name FORCED Delete
    git branch - m new-name-for-branch
    git branch - a list all remote branches


    10) git remote add new-remote-repo https://bitbucket.com/user/repo.git
    # Add remote repo to local repo config
    git push crazy-experiment
    # pushes the crazy-experiment branch to new-remote-repo


    11) To delete remote repo
    git push origin - -delete remote-branch-name
    Or git push origin :branchName
    If you forget to add a file in recently made commit or added wronf message then stage the files using git add and then make
    git commit --amend
    to make change in the last commit only without creating new commit


    12) To make changes in previous commit or change staging area
    git commit - -amend
    git remote lists all the remote handles you have specified.
    git remote add new-remote-name https://github.com/paulboone/ticgit
    git remote -v


    13) git fetch
    git fetch pb
    Will fetch all the code and branches of pb remote made by (Paul Branson ) and we can inspect all the changes and code of his branches (pb/master and pb/local-branch-names will be available for us )


    14) Remote
    When we clone a project a new remote automatically gets created named origin
    git fetch
    git fetch origin fetches all the changes that have been Made in server after your last fetch
    NOTE : fetch command just download the data from server but does not merge it with your work on the other hand git pull command will fetch the changesets introduced on serve will fetch it and then merge it in your project.

    git remote show will stat all info about particular remote along with all the remotest branches for that remote.


    Renaming Remote
    git remote rename pb paul
    Will change remote branch name from pb to Paul

    git remote rename
    git remote remove
    git remote show
    For git remote show origin it will show the fetch and push URL for remote it will list all the remote repositories for remote also it is will state which local branches are tracking which remote for git push and git pull.



    Removing Remote
    git remote rm paul
    will remove reference to a remote branch, used when you don't want a mirror or a contributor has stopped contributing


    15) master branch is just like any another branch in git only difference is it gets created when we use git init command and most users does not choose to change it's name.

    every commit is snapshot of files for a particular version, after we change our project for the first time let's say we have added 3 new files so 5 things will be saved in the git 3 blobs that will contain the content of files 1 tree that will contain names of the files and which blob is refernced by which file and 5th one is commit that will point it to the tree.


    16) Merging
    Merging can be of two types using
    i) fast-forward
    ii) Recursively merge
    In fast-forward the two branches that have to be merged are on the same commit path i.e., there is no divergent path for two branches
    so the in such case the master is switched directly to the most recently added commit(in this case made by ohter branch).
    While in Recursively merge a new commit is created that is called merge commit , this occurs when the development line is diverged so (the two diverged development line will have a common ancestor somewhere in the past) both the branches will be merged and a new commit known as merge commit is created. A merge commit has two parents instead of one.

    If two diverged line of development represented by two different branches are merged and both have updated the same file and same piece or lines of code then merge conflict will occur and conflict resolution markers will be written in the file with HEAD section conataing the branch in which we are merging code(i.e, generally master.)

    After a hotfix is done delete the branch as it's purpose is completed.


    17) git branch -v will list all the last commits in all the local branch.


    18) Remote tracking branches are local branches that mirror or track a remote branch and it's referenece cannot be changed by user.


    19) git config --global credential.helper cache.
    use this command to avoid entering git credentials every time you want to make a push on remote.


    20) When you are using the concept of tracking a remote branch in a local branch the
    when we clone the remote repository the there are two reference created on out local system one is master and other is origin/master
    when we made any commit in our local branch that is tracking remote the master branch reference is moved and let's say there are some commits made on remote by other user we will use git fetch it will update our local repository and origin/master reference will move and the two branches are diverged in this case master and origin/master, origin/master cannot be changed by you it will alway point to the position of remote's last commit.


    21) git checkout --track origin/serverfix
    Branch serverfix set up to track remote branch serverfix from origin.
    Switched to a new branch 'serverfix'

    In fact, this is so common that there’s even a shortcut for that shortcut. If the branch name you’re trying to checkout
    (a)doesn’t exist and
    (b) exactly matches a name on only one remote,
    Git will create a tracking branch for you:

    git checkout serverfix

    Branch serverfix set up to track remote branch serverfix from origin.
    Switched to a new branch 'serverfix'

    git checkout -b sf origin/serverfix
    Branch sf set up to track remote branch serverfix from origin.
    Switched to a new branch 'sf'


    22)
    git checkout bugFix
    git rebase master
    git checkout master
    git merge bugFix

    this series of commands will rebase the bugFix branch as a linear line of changes in master branch and on merge from master it will
    do a simple fast forwarding merge.

    Note that the snapshot pointed to by the final commit you end up with, whether it’s the last of the rebased commits for a rebase or the final merge commit after a merge, is the same snapshot — it’s only the history that is different. Rebasing replays changes from one line of work onto another in the order they were introduced, whereas merging takes the endpoints and merges them together

    git rebase --onto master server client
    This basically says, “Take the client branch, figure out the patches since it diverged from the server branch, and replay these patches in the client branch as if it was based directly off the master branch instead.” It’s a bit complex, but the result is pretty cool.
    Do not rebase commits that exist outside your repository and people may have based work on them.

    In general the way to get the best of both worlds is to rebase local changes you’ve made but haven’t shared yet before you push them in order to clean up your story, but never rebase anything you’ve pushed somewhere.


    23) Tagging
    Like most VCSs, Git has the ability to tag specific points in a repository’s history as being important. Typically, people use this functionality to mark release points (v1.0, v2.0 and so on).
    Listing Your Tags
    Listing the existing tags in Git is straightforward. Just type git tag (with optional -l or --list):

    git tag

    Creating an annotated tag in Git is simple. The easiest way is to specify -a when you run the tag command:

    git tag -a v1.4 -m "my version 1.4"


    24) Commit Guidelines
    a) submissions should not contain any whitespace errors.
    b) Make one commit per issue with useful message per commit.

    The last thing to keep in mind is the commit message. Getting in the habit of creating quality commit messages makes using and collaborating with Git a lot easier. As a general rule, your messages should start with a single line that’s no more than about 50 characters and that describes the changeset concisely, followed by a blank line, followed by a more detailed explanation. The Git project requires that the more detailed explanation include your motivation for the change and contrast its implementation with previous behavior — this is a good guideline to follow. Write your commit message in the imperative: "Fix bug" and not "Fixed bug" or "Fixes bug."
    i) Separate subject from body with a blank line
    ii) Limit the subject line to 50 characters
    iii) Capitalize the subject line
    iv) Do not end the subject line with a period
    v) Use the imperative mood in the subject line
    vi) Wrap the body at 72 characters
    vii) Use the body to explain what and why vs. how

    Here is a template originally written by Tim Pope:

    Capitalized, short (50 chars or less) summary

    More detailed explanatory text, if necessary. Wrap it to about 72
    characters or so. In some contexts, the first line is treated as the
    subject of an email and the rest of the text as the body. The blank
    line separating the summary from the body is critical (unless you omit
    the body entirely); tools like rebase can get confused if you run the
    two together.

    Write your commit message in the imperative: "Fix bug" and not "Fixed bug"
    or "Fixes bug." This convention matches up with commit messages generated
    by commands like git merge and git revert.

    Further paragraphs come after blank lines.

    - Bullet points are okay, too

    - Typically a hyphen or asterisk is used for the bullet, followed by a
    single space, with blank lines in between, but conventions vary here

    - Use a hanging indent


    25) Stashing
    When you are working on a branch and made some changes suddenly want to checkout to other branch for some urgent work like hotfix of any issue but your present branch is not clean as there must be some modified files which are not staged while some that are staged files but you do not want to commit so you can stash the files and commit it later.
    git stash push to save a stash
    git stash list to list all the present stashes available
    git stash apply stash@{2} for applying particular stash
    git stash apply for applying last stash
    git stash drop stash@{0} for deleting a particular mentioned stash


    26) Issues
    Issues are a great way to keep track of tasks, enhancements, and bugs for your projects. They’re kind of like email—except they can be shared and discussed with the rest of your team. Most software projects have a bug tracker of some kind. GitHub’s tracker is called Issues, and has its own section in every repository.
    -Milestones are groups of issues that correspond to a project, feature, or time period. People use them in many different ways in software development,ex:-
    -Beta Launch
    -October Sprint
    -Redesign
    -Labels
    -Assignees


    Github issues also have feature of
    -Notifications
    -@Mention
    -Reference (to another issue)